package com.xbn.xbnmall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author XBN
 * @date 2020/8/16 15:25
 * @email 78742541@qq.com
 */
@Configuration
public class MyRabbitConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    //构造器执行对象创建之后调用这个方法
    //只要消息代理收到了消息，这个方法就会执行
    @PostConstruct
    public void initRabbitTemplate(){
        //设置消息抵达broker消息服务的确认回调
        rabbitTemplate
                .setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
                    @Override
                    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                        System.out.println("消息确认...成功发送给broker消息服务器  correlationData"
                        +":"+correlationData+"ack"+ack+"cause"+cause);
                    }
                });
        //设置消息抵达队列的确认回调，只要消息没有投递给指定的队列就触发这个失败回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText,
                                        String exchange, String routingKey) {
                System.out.println("消息投递队列失败，消息信息："+message+"回复文本："+replyText
                +"：投递的交换器"+exchange+",路由键"+routingKey);
            }
        });
    }
}
